package org.shock.ss.sms.interceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


import org.apache.log4j.Logger;

import org.shock.ss.sms.bean.system.ProjectLog;
import org.shock.ss.sms.bean.system.UserInfor;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import org.shock.ss.sms.commons.annotation.RightAnno;
import org.shock.ss.sms.commons.db.DbTools;
import org.shock.ss.sms.commons.utils.ExceptionProcess;

/**
 * action全局处理拦截器 
 * 
 * 
 * @author jile
 * 
 */
public class GlobalInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = 6595576398896990716L;

	public void destroy() {

	}

	public void init() {

	}

	public String intercept(ActionInvocation arg0) throws Exception {
		Logger log = Logger.getLogger(getClass());
		try {
			String nav = "";
			// 获得当前执行方法的权限
			String curRight = (arg0.getAction().getClass().getName() + "." + arg0
					.getProxy().getMethod()).replace("org.shock.ss.sms.action.",
					"");
			log.debug(curRight);
			// 获得session
			UserInfor userinfor=new UserInfor();
			try {
				userinfor = (UserInfor) ActionContext.getContext()
						.getSession().get("userinfor");
			} catch (IllegalStateException e) {
				log.error("session已经失效！",e);
			}
			// 获得当前用户所有权限
			List<String> rightList = new ArrayList<String>();
			if (null != userinfor) {
				rightList = userinfor.getRightcodes();
				log.debug(rightList);
			}
			// 获得当前执行的及Annotation
			Method method = arg0.getAction().getClass().getMethod(
					arg0.getProxy().getMethod());
			// 如果Annotation存在，进行权限验证
			if (method.isAnnotationPresent(RightAnno.class)) {
				nav = method.getAnnotation(RightAnno.class).rightNote()+"<span class='helpdoc'>  <a href='javascript:showhelp()'><img src='images/pichelp.gif' border='0' style='margin-top:6px;' alt='帮助'></a></span>";// 用于导航栏显示当前位置
				// 如果当前方法权限不为public并且用户权限中不包含当前方法权限并且不是超级管理员，则提示没有权限，返回登录界面
				if (!hasRight(curRight, rightList)
						&& !method.getAnnotation(RightAnno.class).rightValue()
								.equals("public")
						&& userinfor.getIsadmin() != 1) {
					ActionContext.getContext().getValueStack().set("success",
							false);
					ActionContext.getContext().getValueStack().set("message",
							"没有权限！");
					// ActionContext.getContext().getValueStack().set("jmpUrl","/login.jsp");
					// 如果是ajax请求，则返回ajxsuccess，用于传递json消息
					if (("ajax").equals(ActionContext.getContext()
							.getValueStack().findString("op"))) {
						ActionContext.getContext().getValueStack()
								.set("jsonString",
										"{success:false,message:'没有权限！'}");
						return "ajxsuccess";
					}
					return "error";
				}
				log.debug(method.getAnnotation(RightAnno.class).rightValue());
			}
			ActionContext.getContext().getValueStack().set("nav", nav);
			String str = arg0.invoke();
			if (("ajax").equals(ActionContext.getContext().getValueStack()
					.findString("op"))) {
				str = "ajxsuccess";
				ActionContext.getContext().getValueStack().set(
						"jsonString",
						"{success:"
								+ ActionContext.getContext().getValueStack()
										.findString("success")
								+ ",message:'"
								+ ActionContext.getContext().getValueStack()
										.findString("message") + "'}");

			}
			/** 方法执行完毕后 如果Annotation islog 为true 进行日志记录 */
			if (method.isAnnotationPresent(RightAnno.class)) {
				if (method.getAnnotation(RightAnno.class).islog()) {
					ProjectLog prjlog = (ProjectLog) ActionContext.getContext()
							.getValueStack().findValue("prjlog");
					if (null != userinfor) {
						prjlog.setOpzh(userinfor.getYgzh());
					}
					prjlog.setType(method.getAnnotation(RightAnno.class)
							.rightNote());
					DbTools.addLog(prjlog);
				}
			}
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e, e);// 记录错误
			ActionContext.getContext().getValueStack().set("message",
					ExceptionProcess.localErrMsg(e));
			ActionContext.getContext().getValueStack().set("success", false);
			ActionContext.getContext().getValueStack().set(
					"jsonString",
					"{success:false,message:'"
							+ JSON.toJSONString(ExceptionProcess.localErrMsg(e)) + "'}");
			if (("ajax").equals(ActionContext.getContext().getValueStack()
					.findString("op"))) {
				return "ajxsuccess";
			}
			return "error";
		}

	}

	private boolean hasRight(String str, List list) {
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).toString().trim().equals(str)) {
				return true;
			}
		}
		return false;
	}
}
